package com.morgankelly.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.orm.jdo.support.JdoDaoSupport;

import com.morgankelly.po.BasePO;
import com.morgankelly.util.PMF;

@SuppressWarnings("unchecked")
public abstract class GenericDAO<T extends BasePO> extends JdoDaoSupport
		implements IGenericDAO<T> {

	private Class<T> entityClass;

	public GenericDAO() {
		entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	@Override
	public long listSize() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		long size = 0;
		Query query = pm.newQuery("select count(id) from " + entityClass.getName());
		size = Long.parseLong(query.execute().toString());
		return size; 
	}
	
	@Override
	public void add(BasePO obj) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		pm.makePersistent(obj);
	}

	@Override
	public void delete(BasePO obj) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.deletePersistent(obj);
	}

	@Override
	public void deleteByID(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		pm.deletePersistent(pm.getObjectById(entityClass, id));
	}

	@Override
	public T findByID(Long id) {
		
		PersistenceManager pm = PMF.get().getPersistenceManager();

		return pm.getObjectById(entityClass, id);
	}

	@Override
	public List<T> findAll() {
		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(entityClass);
		return (List<T>) query.execute();
	}

	@Override
	public List<T> findByProp(Map value) {
		//TODO:
		return null;
	}
}
